﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

using Seven.Entity;
using Seven.EntityBasic;
using Seven.DataModel.ViewModels.MenuAbout;
using Seven.Tools.Extension;
using Seven.Tools.Helper;

namespace Seven.Service.Powerful
{
    public partial class SysMenuFunctionService
    {
        /// <summary>
        /// 根据菜单功能点IDs集合获取该用户的菜单功能点集合
        /// </summary>
        /// <param name="functionIds">菜单功能点IDs集合</param>
        /// <param name="includeMenu">是否同时查询导航属性-菜单的数据</param>
        /// <returns></returns>
        public IEnumerable<SysMenuFunction> GetRangeMenuFunctions(IEnumerable<string> functionIds, bool includeMenu = false)
        {
            if (functionIds.Count() == 0) { return new List<SysMenuFunction>(); }

            string ids = string.Join(",", functionIds);
            var arr = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (arr.Count() == 0) { return new List<SysMenuFunction>(); }

            using (var unit = DbFactory.UnitOfWork)
            {
                return unit.SysMenuFunction.GetMenuFunctionsByIDs(arr.ToInt(), includeMenu);
            }
        }

        /// <summary>
        /// 根据用户ID获取该用户的菜单功能点集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="all">是否获取全部，默认否。若是，将忽略权限。</param>
        /// <param name="includeMenu">是否同时查询导航属性-菜单的数据</param>
        /// <returns></returns>
        public IEnumerable<SysMenuFunction> GetRangeMenuFunctions(int userId, bool all, bool includeMenu = false)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                if (!all)
                {
                    IList<int> menuPermissionIDs = new List<int>();
                    #region 获取该用户可用的的菜单权限ID集合
                    IEnumerable<SysUserMenuPermission> userPermissions = unit.SysUserMenuPermission.GetUserMenuPermissions(userId);
                    IEnumerable<SysRoleMenuPermission> rolePermissions = rolePermissions = unit.SysRoleMenuPermission.GetRoleMenuPermissionsByUserID(userId);
                    if (userPermissions.Count() > 0)
                    {
                        #region 若用户权限不为空，则遍历用户权限集合，结合角色权限进行合并

                        foreach (var item in userPermissions)
                        {
                            if (item.Check && !item.Indeterminate)
                            {
                                //用户权限 打勾且选中
                                menuPermissionIDs.Add(item.MenuPermissionID);
                            }
                            else if (item.Check && item.Indeterminate)
                            {
                                //用户权限 打勾不选中
                                if (rolePermissions.Any(a => a.MenuPermissionID == item.MenuPermissionID && a.Check))
                                {
                                    menuPermissionIDs.Add(item.MenuPermissionID);
                                }
                            }
                        }

                        #endregion
                    }
                    else
                    {
                        menuPermissionIDs = rolePermissions.Where(w => w.Check).Select(s => s.MenuPermissionID).ToList();
                    }
                    #endregion

                    var functionIds = menuPermissionIDs.Count() > 0 ? unit.SysMenuPermission.GetMenuFunctionIDs(menuPermissionIDs) : new List<string>();
                    if (functionIds.Count() == 0) { return new List<SysMenuFunction>(); }

                    string ids = string.Join(",", functionIds);
                    var arr = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (arr.Count() == 0) { return new List<SysMenuFunction>(); }

                    return unit.SysMenuFunction.GetMenuFunctionsByIDs(arr.ToInt(), includeMenu);
                }
                else
                { return unit.SysMenuFunction.GetAllMenuFunctions(includeMenu); }
            }
        }

        #region 获取ViewModel

        /// <summary>
        /// 根据菜单ID获取新的菜单功能点模型
        /// </summary>
        /// <param name="menuId">菜单ID</param>
        /// <returns></returns>
        public MenuFunctionModel GetNewMenuFunctionModel(int menuId)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                var data = unit.SysMenu.GetSimpleModelByID(menuId);

                var model = new MenuFunctionModel { MenuID = menuId, IsShow = true };
                model.MenuName = data.Name;
                model.ControllerName = data.ControllerName;
                model.ActionName = data.FunctionCount == 0 ? data.ActionName : "";

                return model;
            }
        }

        /// <summary>
        /// 根据菜单功能点ID获取供编辑的数据模型
        /// </summary>
        /// <param name="id">菜单功能点ID</param>
        /// <returns></returns>
        public MenuFunctionModel GetEditMenuFunctionModel(int id)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                return unit.SysMenuFunction.GetEditModelByID(id);
            }
        }

        #endregion

        #region 提供json数据

        /// <summary>
        /// 提供功能点类型json数据
        /// </summary>
        /// <returns></returns>
        public JsonResult FunctionTypeJson()
        {
            var Types = EnumHelper.GetEnumItems<FunctionType>(typeof(FunctionType));

            return new DataResult(Types.Select(s => new { s.Value, s.Text })).SerializeToJsonResult();
        }

        /// <summary>
        /// 提供菜单功能点json数据
        /// </summary>
        /// <param name="menuId">菜单ID</param>
        /// <returns></returns>
        public JsonResult MenuFunctionJson(int menuId)
        {
            IEnumerable<SysMenuFunction> data;
            using (var unit = DbFactory.UnitOfWork)
            {
                data = unit.SysMenuFunction.GetMenuFunctionsByMenuID(menuId);
            }

            return new DataResult(data.Select(s => new { s.ID, FunctionName = s.Name, s.ActionName, FunctionType = s.Type.ToString() })).SerializeToJsonResult();
        }

        /// <summary>
        /// 提供菜单功能点json数据
        /// </summary>
        /// <param name="menuId">菜单ID</param>
        /// <returns></returns>
        public JsonResult MenuFunctionJson1(int menuId)
        {
            IEnumerable<SysMenuFunction> data;
            using (var unit = DbFactory.UnitOfWork)
            {
                data = unit.SysMenuFunction.GetMenuFunctionsByMenuID(menuId);
            }

            return new DataResult(data.Select(s => new { s.ID, Name = s.Name + "[" + s.Type.ToString() + "]", s.ActionName })).SerializeToJsonResult();
        }

        #endregion

        #region CUD操作

        /// <summary>
        /// 保存菜单功能点
        /// </summary>
        /// <param name="model">菜单数据模型</param>
        /// <returns></returns>
        public JsonResult SaveMenuFunction(MenuFunctionModel model)
        {
            SysMenuFunction entity;
            if (model.ID == 0)
            {
                entity = model.CopyTo<SysMenuFunction>();

                return this.Insert(entity).SerializeToJsonResult();
            }
            else
            {
                entity = this.GetByKey(model.ID);
                entity.Name = model.Name;
                entity.Type = model.Type;
                entity.SortNumber = model.SortNumber;
                entity.ActionName = model.ActionName;
                entity.ActionDescription = model.ActionDescription;
                entity.IsShow = model.IsShow;
                entity.Remark = model.Remark;

                return this.Update(entity).SerializeToJsonResult();
            }
        }

        /// <summary>
        /// 移除菜单功能点
        /// </summary>
        /// <param name="id">菜单功能点id</param>
        /// <returns></returns>
        public JsonResult RemoveMenuFunction(int id)
        {
            var entity = this.GetByKey(id);
            if (entity == null) { return new OperationResult(false, "菜单功能点不存在！").SerializeToJsonResult(); }

            return this.Delete(entity).SerializeToJsonResult();
        }

        #endregion
    }
}
